package com.weiya.commons.codec;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * Created with eden
 *
 * @Author: bailong Date: 2018/1/10 Time: 下午11:11 北京伊电园网络科技有限公司 2016-2017 © 版权所有 京ICP备17000101号
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MD5Utils {

    /**
     * 获取简单MD5值
     */
    public static String simpleStringMD5(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] inputByteArray = data.getBytes(Charset.forName("UTF-8"));
            messageDigest.update(inputByteArray);
            byte[] resultByteArray = messageDigest.digest();
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * 获取加盐MD5
     */
    public static String Md5WithSalt(String data, String salt) {
        data = salt + data;
        return simpleStringMD5(data);
    }

    /**
     * 获取简单MD5值
     */
    public static String encrypt(String plaintext) {
        return DigestUtils.md5Hex(plaintext.getBytes());
    }

    /**
     * 获取加盐MD5
     */
    public static String encrypt(String plaintext, String salt) {
        return DigestUtils.md5Hex(salt + plaintext);
    }

    /**
     * 字节数组转16进制
     */
    private static String byteArrayToHex(byte[] byteArray) {
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] resultCharArray = new char[byteArray.length * 2];
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArray);
    }

}
